<template>
  <div class="upload box bg clmcenter">
    <div class="backbox">
      <img
        src="@/assets/img/back.png"
        class="goback"
        @click="$router.replace({ path: '/index', query: { intxt: 'back' } })"
      />
    </div>
    <div class="uploadbox">
      <div class="addrnamebox">
        <p class="addrname">{{ name }}</p>
      </div>
      <div class="uploadcont">
        <img :src="userimgsrc" class="userimgsrc" />
        <input
          type="file"
          ref="fileRef"
          accept="image/*"
          @change="onFileChange"
        />
      </div>
    </div>
    <div class="uptips">
      <p>拍摄照片要求：</p>
      <p>1. 出现打卡地相关318元素+摩托车</p>
      <p>2. 照片请符合平台规范</p>
    </div>
    <div class="upbtnbox">
      <div class="rechosebox">
        <img
          src="@/assets/img/btn_rechoose.png"
          class="rechoose"
          @click="rechooseFile"
        />
        <input
          type="file"
          ref="fileRef2"
          accept="image/*"
          @change="rechooseFile"
        />
      </div>
      <img
        src="@/assets/img/btn_upload.png"
        class="uploadbtn"
        @click="uploadToNext"
      />
    </div>
    <el-dialog
      class="cropperbox"
      :visible.sync="dialogVisible"
      @opened="onDialogOpend"
      :modal="false"
      :modal-append-to-body="true"
      :append-to-body="true"
    >
      <div class="preview-image-warp clmcenter">
        <img class="preview-image" :src="previewImage" ref="previewImg" />
      </div>
      <div class="cropperbtnbox">
        <button @click="cancleCutImg">取消</button>
        <button @click="onUpdataPhoto">确认</button>
      </div>
    </el-dialog>
    <!-- 打卡失败 -->
    <div class="tkbox failbox clmcenter" v-show="uperrflag">
      <div class="tkcontainer clmcenter">
        <div class="tk_container clmstart">
          <p class="title">打卡失败</p>
          <div class="tk_infobox">
            <div class="tk_info clmcenter">
              <img src="@/assets/img/cuo.png" />
              <p>
                抱歉，超出打卡范围<br />
                请返回位置重新打卡
              </p>
            </div>
          </div>
        </div>
        <img
          src="@/assets/img/close.png"
          class="backtoinfo"
          @click="uperrflag = false"
        />
      </div>
    </div>
    <!-- 打卡成功-附近门店 -->
    <div class="tkbox nearstorebox clmcenter" v-show="nearstoreflag">
      <div class="tk_container">
        <div class="tk_title">- 恭喜获得{{ prizeInfo.prize }} -</div>
        <div class="tk_imgbox clmcenter">
          <img :src="nearStoreInfo.img_url" class="nearstoreimg" />
        </div>
        <div
          class="tk_storename"
          @click="
            mapTo(
              nearStoreInfo.latitude,
              nearStoreInfo.longitude,
              nearStoreInfo.name
            )
          "
        >
          <span>{{ nearStoreInfo.name }}</span>
        </div>
      </div>
      <div class="tk_btnbox">
        <img
          src="@/assets/img/btn_next.png"
          class="btn_next"
          @click="toLottery"
        />
        <img
          src="@/assets/img/btn_back_gray.png"
          class="btn_back"
          @click="$router.replace({ path: '/index', query: { intxt: 'back' } })"
        />
      </div>
    </div>
  </div>
</template>
<script>
import { Toast } from "vant";
import wx from "weixin-js-sdk";
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.min.css";
export default {
  data() {
    return {
      userimgsrc: require("@/assets/img/tips.png"),
      previewImage: "",
      dialogVisible: false,
      cropper: null, // 裁切器实例
      chooseflag: false, //用来判断用户是否选择了照片
      uperrflag: false, //打卡失败
      nearstoreflag: false, //附近门店
      location_id: "",
      latitude: 0,
      longitude: 0,
      name: "遇尚理塘时尚餐厅民宿",
      prizeInfo: {
        prize: "",
        prizeId: "",
        wid: "",
        exch_method: "",
        type: "",
        status: "",
      },
      nearStoreInfo: {},
    };
  },
  mounted() {
    let pm = this.$route.params;
    this.location_id = pm.location_id;
    this.latitude = pm.latitude;
    this.longitude = pm.longitude;
    this.prizeInfo.type = pm.type;
    this.name = pm.name;
  },
  methods: {
    //下一步
    uploadToNext() {
      if (!this.chooseflag) {
        Toast("请选择图片");
      } else {
        Toast.loading({
          message: "loading...",
          forbidClick: true,
          duration: 0, //值为 0 时，toast 不会消失
          overlay: true, //是否显示背景遮罩层
        });
        let postParams = {
          id: this.location_id,
          latitude: this.latitude,
          longitude: this.longitude,
          img: this.userimgsrc,
          type: this.prizeInfo.type,
        };
        this.$http.post("/userSignAndGetPrize", postParams).then((res) => {
          Toast.clear();
          // console.log(res);
          if (res.data.code == 200) {
            //打卡成功
            let info = res.data.data;
            this.prizeInfo.prize = info.prize;
            this.prizeInfo.prizeId = info.prizeId;
            this.prizeInfo.wid = info.wid;
            this.prizeInfo.exch_method = info.exch_method;
            this.prizeInfo.status = info.status;
            if (this.prizeInfo.type == "1") {
              // 门店打卡 直接到抽奖页面
              this.$router.replace({
                name: "lottery",
                params: {
                  prize: info.prize,
                  prizeId: info.prizeId,
                  wid: info.wid,
                  exch_method: info.exch_method,
                  type: this.prizeInfo.type,
                  status: info.status,
                },
              });
            } else {
              // 景点打卡 弹出附近门店，点击下一步到抽奖页面
              this.nearStoreInfo = {
                name: info.nearestStore.name,
                img_url: info.nearestStore.poster_url,
                latitude: info.nearestStore.latitude,
                longitude: info.nearestStore.longitude,
              };
              this.nearstoreflag = true;
            }
          } else if (res.data.code == -1) {
            this.uperrflag = true;
          } else {
            Toast(res.data.msg);
          }
        });
      }
    },
    // 附近门店点击 去抽奖
    toLottery() {
      this.$router.replace({
        name: "lottery",
        params: {
          prize: this.prizeInfo.prize,
          prizeId: this.prizeInfo.prizeId,
          wid: this.prizeInfo.wid,
          exch_method: this.prizeInfo.exch_method,
          type: this.prizeInfo.type,
          status: this.prizeInfo.status,
        },
      });
    },
    //打开地图
    mapTo(latitude, longitude, name) {
      var url = encodeURIComponent(window.location.href.split("#")[0]);
      this.$http
        .post("https://www.mahelei.com/index.php/Gm/Wechat/share", { url })
        .then((res) => {
          let data = res.data;
          wx.config({
            debug: false,
            appId: data.appId,
            timestamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.signature,
            jsApiList: ["checkJsApi", "openLocation"],
            success(res) {
              //   Toast(res);
            },
          });
        });
      wx.ready(() => {
        wx.checkJsApi({
          jsApiList: ["openLocation"],
          success: (rest) => {
            //打开指定位置
            wx.openLocation({
              latitude: latitude, // 纬度，浮点数，范围为90 ~ -90
              longitude: longitude, // 经度，浮点数，范围为180 ~ -180。
              name: name, // 位置名
              address: "", // 地址详情说明
              scale: 18, // 地图缩放级别,整型值,范围从1~28。默认为最大
              infoUrl: "", // 在查看位置界面底部显示的超链接,可点击跳转
            });
          },
        });
      });
    },
    //重新选择
    rechooseFile() {
      var that = this;
      const file = this.$refs.fileRef2;
      var reader = new FileReader();
      reader.readAsDataURL(file.files[0]);
      reader.onload = function (e) {
        that.previewImage = e.target.result;
        that.dialogVisible = true;
        file.value = "";
        that.onDialogOpend();
      };
    },
    //选择照片
    onFileChange() {
      var that = this;
      const file = this.$refs.fileRef;
      var reader = new FileReader();
      reader.readAsDataURL(file.files[0]);
      reader.onload = function (e) {
        that.previewImage = e.target.result;
        that.dialogVisible = true;
        file.value = "";
        that.onDialogOpend();
      };
    },
    onDialogOpend() {
      if (this.cropper) {
        this.cropper.replace(this.previewImage);
        return;
      }
      const cimg = this.$refs.previewImg;
      // 初始化裁切器
      this.cropper = new Cropper(cimg, {
        aspectRatio: 5.98 / 4.15, // 初始化剪切选择框大小
        viewMode: 1, // 不能把剪切框移出图片本身
        canMove: true, //上传的图片是否可以移动
        dragMode: "move", //不能移动裁剪框
        cropBoxMovable: false, //允许通过拖动移动裁剪框。默认true
        cropBoxResizable: false, //以通过拖动来调整裁剪框的大小 默认true
        // movable: true, //移动图像
      });
    },
    // 点击对话框确定按钮，更新修改后的图片
    onUpdataPhoto() {
      Toast.loading({
        message: "loading...",
        forbidClick: true,
        duration: 0, //值为 0 时，toast 不会消失
        overlay: true, //是否显示背景遮罩层
      });
      var imgURL = this.cropper.getCroppedCanvas().toDataURL("image/png");
      this.previewImage = imgURL;
      //不压缩
      this.userimgsrc = imgURL;
      this.dialogVisible = false;
      this.chooseflag = true;
      Toast.clear();
      //压缩
      // let base64 = imgURL;
      // this.compressImage(base64, 500, this.useImg);
    },
    //点击对话框取消按钮，恢复默认状态
    cancleCutImg() {
      this.previewImage = "";
      this.dialogVisible = false;
      this.chooseflag = false;
    },
  },
};
</script>

<style lang="less" scoped>
.upload {
  .uploadbox {
    position: relative;
    width: 686px;
    height: 828px;
    margin-top: 3rem;
    background: url("@/assets/img/uploadbox.png") no-repeat;
    background-size: contain;
    display: flex;
    flex-flow: column nowrap;
    justify-content: flex-end;
    align-items: center;
    .addrnamebox {
      width: 394px;
      margin-bottom: 11.5rem;
      margin-left: 5rem;
      .addrname {
        font-family: "AlibabaPuHuiTi-2-85-Bold";
        font-weight: bold;
        font-size: 2.7rem;
        color: #de0205;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .uploadcont {
      position: relative;
      width: 598px;
      height: 415px;
      border-radius: 1rem;
      overflow: hidden;
      margin-bottom: 4.2rem;
      margin-left: 3px;
      img {
        width: 100%;
      }
      input {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
      }
    }
  }
  .uptips {
    align-self: flex-start;
    width: 63.5%;
    margin-top: 1rem;
    margin-left: 5rem;
    p {
      font-size: 1.9rem;
      color: #de0205;
    }
    p:first-child {
      font-size: 2.2rem;
      color: #000000;
    }
  }
  .upbtnbox {
    margin-top: 3rem;
    width: 100%;
    display: flex;
    place-content: center center;
    .uploadbtn,
    .rechosebox {
      width: 36%;
      margin: 0 1rem;
    }
    .rechosebox {
      position: relative;
      height: 78px;
      img {
        width: 100%;
      }
      input {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
      }
    }
  }
  //   上传失败
  .failbox {
    .tkcontainer {
      .tk_container {
        .tk_infobox {
          .tk_info {
            img {
              margin-top: 2rem;
            }
            p {
              font-size: 2rem;
              padding-top: 1rem;
              text-align: center;
            }
          }
        }
      }
      .backtoinfo {
        margin-top: 5rem;
      }
    }
  }
  // 附近门店
  .nearstorebox {
    .tk_container {
      width: 695px;
      height: 760px;
      background: url("@/assets/img/nearbg.png") no-repeat;
      background-size: 100% 100%;
      .tk_title {
        width: 97%;
        height: 85px;
        line-height: 85px;
        margin-top: 1rem;
        margin-left: 0.5rem;
        text-align: center;
        font-size: 2.5rem;
        color: #de0205;
        font-family: "AlibabaPuHuiTi-2-85-Bold";
      }
      .tk_imgbox {
        width: 605px;
        height: 397px;
        margin-top: 4.9rem;
        margin-left: 2.4rem;
        clip-path: polygon(
          0 0,
          98% 0,
          100% 13px,
          100% 100%,
          67% 100%,
          65% 97%,
          0 97%
        );
        overflow: hidden;
        .nearstoreimg {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      .tk_storename {
        width: 81%;
        height: 50px;
        margin-top: 1.7rem;
        margin-left: 6rem;
        line-height: 50px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        span {
          max-width: 100%;
          height: 100%;
          font-size: 2rem;
          color: #404040;
          padding: 0 1rem;
          border-bottom: 2px solid #003c88;
          box-sizing: border-box;
        }
      }
      .tk_btnbox {
        width: 100%;
        margin-top: 3rem;
        display: flex;
        justify-content: center;
        align-items: center;
        img {
          margin: 0 1rem;
        }
      }
    }
    .tk_btnbox {
      width: 100%;
      margin-top: 3rem;
      display: flex;
      justify-content: center;
      align-items: center;
      img {
        margin: 0 1rem;
      }
    }
  }
}
@media only screen and (min-height: 1300px) {
  .upload {
    .uploadbox {
      margin-top: 2rem;
    }
    .upbtnbox {
      margin-top: 4rem;
    }
  }
}
@media only screen and (min-height: 1400px) {
  .upload {
    .uploadbox {
      margin-top: 0;
    }
    .upbtnbox {
      margin-top: 5rem;
    }
  }
}
</style>
<style>
.cropperbox {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #fff;
  z-index: 99;
}
.preview-image-warp {
  width: 100%;
  height: 100%;
}
.preview-image {
  display: block;
  max-width: 100%;
  height: 300px;
}
.cropperbtnbox {
  position: absolute;
  bottom: 5rem;
  width: 100%;
  text-align: center;
}
.cropperbtnbox button {
  width: 200px;
  height: 75px;
  margin: 0 2rem;
  font-size: 2rem;
  border-style: none;
  border-radius: 10px;
  background: #ffffff;
  color: #000;
}
.cropperbtnbox button:last-child {
  background: #3399ff;
  color: #fff;
}
.el-dialog__body,
.el-dialog__header {
  padding: 0 !important;
}
.el-dialog__body {
  width: 100% !important;
  height: 100% !important;
}
.el-dialog__headerbtn {
  display: none !important;
}
.el-dialog {
  margin: 0 !important;
  width: 100% !important;
  height: 100% !important;
}
.cropper-canvas {
  width: 100% !important;
}
.cropper-bg {
  width: 750px !important;
  height: 100% !important;
}
</style>
